import axios from "axios";
import { useUserStore } from "../store/user";
import { message } from "../utils/message";
import { getDeviceFingerprint } from "../utils/device";

const RAW_PREFIX = import.meta.env.VITE_SERVER_API ?? "";
const API_PREFIX = RAW_PREFIX ? RAW_PREFIX.replace(/\/$/, "") : undefined;

const http = axios.create({
  baseURL: API_PREFIX,
  timeout: 10000
});

http.interceptors.request.use(
  config => {
    config.headers = {
      Accept: "application/json, text/plain, */*",
      "Content-Type": "application/json",
      "X-Client-Mark": "buyer-web",
      "X-Device-Fingerprint": getDeviceFingerprint(),
      ...(config.headers || {})
    };
    const userStore = useUserStore();
    const accessToken = userStore.token?.accessToken;
    const partialToken = userStore.partial?.token;
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    } else if (partialToken) {
      config.headers.Authorization = `Bearer ${partialToken}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

http.interceptors.response.use(
  response => {
    const payload = response.data;
    if (payload && payload.success === false) {
      const err = new Error(payload.msg || "请求失败");
      message.error(err.message);
      return Promise.reject(err);
    }
    return response;
  },
  error => {
    const userStore = useUserStore();
    if (error.response?.status === 401) {
      if (userStore.isLoggedIn) {
        userStore.forceLogout("登录已过期，请重新登录");
      } else if (userStore.partial?.token) {
        userStore.clearPartial();
        message.error("登录流程已过期，请重新登录");
      }
    } else if (error.message) {
      message.error(error.message);
    }
    return Promise.reject(error);
  }
);

export default http;
